<!DOCTYPE html>
<html lang="zh-CN">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>连通性监测</title>
	<style>
		* {
			margin: 0;
			padding: 0;
			box-sizing: border-box;
			font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
		}

		body {
			background-color: #f5f7fa;
			padding: 10px;
			color: #333;
			font-size: 13px;
		}

		.header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 10px;
			padding: 8px 12px;
			background: white;
			border-radius: 6px;
			box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
		}

		.title {
			font-size: 16px;
			font-weight: bold;
			color: #1a1a1a;
		}

		.controls {
			display: flex;
			align-items: center;
			gap: 8px;
		}

		.refresh-label {
			font-size: 12px;
			color: #666;
		}

		.refresh-select {
			padding: 5px 8px;
			border: 1px solid #dcdfe6;
			border-radius: 3px;
			background-color: #fff;
			font-size: 12px;
			outline: none;
			cursor: pointer;
		}

		.refresh-btn {
			padding: 5px 10px;
			background-color: #409eff;
			color: white;
			border: none;
			border-radius: 3px;
			cursor: pointer;
			font-size: 12px;
			transition: background-color 0.2s;
		}

		.refresh-btn:hover {
			background-color: #66b1ff;
		}

		.loading-container {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 80px;
			background: rgba(255, 255, 255, 0.8);
			border-radius: 6px;
			margin-top: 10px;
		}

		.loading {
			display: inline-block;
			width: 30px;
			height: 30px;
			border: 3px solid rgba(64, 158, 255, 0.2);
			border-radius: 50%;
			border-top-color: #409eff;
			animation: spin 1s linear infinite;
		}

		@keyframes spin {
			to { transform: rotate(360deg); }
		}

		.node-group {
			background-color: white;
			border-radius: 6px;
			box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
			margin-bottom: 15px;
			overflow: hidden;
		}

		.group-header {
			padding: 8px 12px;
			background: #f0f7ff;
			border-bottom: 1px solid #e1e4e8;
			font-size: 14px;
			font-weight: bold;
			color: #1a73e8;
		}

		.group-content {
			padding: 10px;
			display: grid;
			grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
			gap: 10px;
		}

		.data-block {
			border-radius: 4px;
			padding: 10px;
			cursor: pointer;
			position: relative;
			overflow: hidden;
			border-left: 4px solid;
			min-height: 80px;
			transition: all 0.2s;
		}

		.data-block:hover {
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
			transform: translateY(-2px);
		}

		.success {
			background: #f0f9eb;
			border-left-color: #4caf50;
		}

		.failed {
			background: #fef0f0;
			border-left-color: #f44336;
		}

		.timeout {
			background: #fdf6ec !important;
			border-left-color: #ff9800 !important;
		}

		.block-title {
			font-weight: bold;
			font-size: 13px;
			margin-bottom: 5px;
			color: #1a1a1a;
			white-space: nowrap;
			overflow: hidden;
			position: relative;
		}

		.block-row {
			font-size: 11px;
			color: #555;
			line-height: 1.4;
			margin-bottom: 2px;
			white-space: nowrap;
			overflow: hidden;
			position: relative;
		}

		.no-data {
			grid-column: 1 / -1;
			text-align: center;
			padding: 15px;
			color: #999;
			font-size: 13px;
		}

		.status-indicator {
			position: absolute;
			top: 8px;
			right: 8px;
			width: 8px;
			height: 8px;
			border-radius: 50%;
		}

		.success .status-indicator {
			background-color: #4caf50;
		}

		.failed .status-indicator {
			background-color: #f44336;
		}

		.timeout .status-indicator {
			background-color: #ff9800;
		}

		/* 滚动文本容器 */
		.scroll-container {
			position: relative;
			overflow: hidden;
			height: 18px;
		}

		.scroll-text {
			position: absolute;
			white-space: nowrap;
			padding-right: 20px;
		}

		/* 鼠标悬停提示框样式 */
		.tooltip {
			position: absolute;
			bottom: 100%;
			left: 50%;
			transform: translateX(-50%);
			background: rgba(0, 0, 0, 0.85);
			color: white;
			padding: 8px 12px;
			border-radius: 4px;
			font-size: 12px;
			white-space: nowrap;
			z-index: 1000;
			opacity: 0;
			visibility: hidden;
			transition: all 0.3s ease;
			pointer-events: none;
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
		}

		.data-block:hover .tooltip {
			opacity: 1;
			visibility: visible;
		}

		.tooltip::after {
			content: '';
			position: absolute;
			top: 100%;
			left: 50%;
			transform: translateX(-50%);
			border: 5px solid transparent;
			border-top-color: rgba(0, 0, 0, 0.85);
		}
	</style>
</head>
<body>
<div class="header">
	<div class="title"></div>
	<div class="controls">
		<span class="refresh-label">刷新间隔：</span>
		<select class="refresh-select" id="refreshInterval">
			<option value="1" selected>1分钟</option>
			<option value="2">2分钟</option>
			<option value="5">5分钟</option>
			<option value="10">10分钟</option>
		</select>
		<button class="refresh-btn" id="manualRefresh">刷新数据</button>
	</div>
</div>

<div id="content">
	<div class="loading-container">
		<div class="loading"></div>
	</div>
</div>

<script>
	// 获取URL参数
	function getUrlParams() {
		const params = new URLSearchParams(window.location.search);
		return {
			categoryIds: params.get('categoryIds') ? params.get('categoryIds').split(',') : [],
			code: params.get('code') || 'ping_v4'
		};
	}

	// 检查数据是否超时（超过5分钟）
	function isDataTimeout(timeStr) {
		const dataTime = new Date(timeStr);
		const currentTime = new Date();
		const diffInMinutes = (currentTime - dataTime) / (1000 * 60);
		return diffInMinutes > 5;
	}

	// 添加滚动效果
	function addScrollEffect() {
		const scrollContainers = document.querySelectorAll('.scroll-container');

		scrollContainers.forEach(container => {
			const text = container.querySelector('.scroll-text');
			if (!text) return;

			const containerWidth = container.offsetWidth;
			const textWidth = text.scrollWidth;

			if (textWidth > containerWidth) {
				const duration = Math.max(5, textWidth / 30); // 根据文本长度调整滚动速度

				// 添加滚动动画
				text.style.animation = `scrollText ${duration}s linear infinite`;

				// 定义滚动动画
				const style = document.createElement('style');
				style.textContent = `
                        @keyframes scrollText {
                            0% { transform: translateX(0); }
                            100% { transform: translateX(${containerWidth - textWidth}px); }
                        }
                    `;
				document.head.appendChild(style);
			}
		});
	}

	// 渲染数据
	function renderData(data, code) {
		const content = document.getElementById('content');
		content.innerHTML = '';

		const { categoryIds } = getUrlParams();

		if (categoryIds.length === 0) {
			content.innerHTML = `
                    <div class="no-data">
                        <div>未选择任何设备类别</div>
                        <div style="margin-top:5px;font-size:11px">请在URL参数中指定categoryIds</div>
                    </div>
                `;
			return;
		}

		if (!data || Object.keys(data).length === 0) {
			content.innerHTML = `
                    <div class="no-data">
                        <div>未获取到监控数据</div>
                        <div style="margin-top:5px;font-size:11px">请检查网络连接或刷新页面</div>
                    </div>
                `;
			return;
		}

		categoryIds.forEach(categoryId => {
			const node = data[categoryId];
			if (!node) return;

			const groupDiv = document.createElement('div');
			groupDiv.className = 'node-group';

			const headerDiv = document.createElement('div');
			headerDiv.className = 'group-header';
			headerDiv.textContent = node.name;

			const contentDiv = document.createElement('div');
			contentDiv.className = 'group-content';

			if (node.collectData && node.collectData.length > 0) {
				node.collectData.forEach(item => {
					const blockDiv = document.createElement('div');

					// 确定状态类
					let statusClass = item.status === 'success' ? 'success' : 'failed';

					// 检查是否超时（成功状态且超时才显示超时）
					if (statusClass === 'success' && isDataTimeout(item.time)) {
						statusClass = 'timeout';
					}

					blockDiv.className = `data-block ${statusClass}`;

					// 显示地址
					const address = code === 'ping_v6' ? item.nodeIpV6 : item.nodeIp;

					// 状态文本
					let statusText = "";
					if (statusClass === 'success') {
						statusText = "正常";
					} else if (statusClass === 'failed') {
						statusText = "异常";
					} else if (statusClass === 'timeout') {
						statusText = "超时异常";
					}

					// 创建tooltip内容
					const tooltipContent = `名称: ${item.nodeNameShow} | 地址: ${address}`;

					// 紧凑布局
					blockDiv.innerHTML = `
                            <div class="status-indicator"></div>
                            <div class="tooltip">${tooltipContent}</div>
                            <div class="scroll-container">
                                <div class="scroll-text">${item.nodeNameShow}</div>
                            </div>
                            <div class="block-row">
                                <div class="scroll-container">
                                    <div class="scroll-text">状态: ${statusText} | 延迟: ${item.delay} ms</div>
                                </div>
                            </div>
                            <div class="block-row">
                                <div class="scroll-container">
                                    <div class="scroll-text">地址: ${address}</div>
                                </div>
                            </div>
                            <div class="block-row">
                                <div class="scroll-container">
                                    <div class="scroll-text">时间: ${item.time}</div>
                                </div>
                            </div>
                        `;

					// 点击事件
					blockDiv.onclick = () => {
						window.open(`/business/ops/monitor_node_resource/monitor_node_collect_data_graph.html?nodeId=${item.id}`, '_blank');
					};

					contentDiv.appendChild(blockDiv);
				});
			} else {
				const noDataDiv = document.createElement('div');
				noDataDiv.className = 'no-data';
				noDataDiv.textContent = '暂无监控数据';
				contentDiv.appendChild(noDataDiv);
			}

			groupDiv.appendChild(headerDiv);
			groupDiv.appendChild(contentDiv);
			content.appendChild(groupDiv);
		});

		// 添加滚动效果
		setTimeout(addScrollEffect, 100);
	}

	// 从API获取数据
	async function fetchData() {
		const { categoryIds, code } = getUrlParams();
		const refreshInterval = document.getElementById('refreshInterval');
		const minutes = parseInt(refreshInterval.value);

		try {
			const response = await fetch(
					`/service-ops/monitor-process-ping/query-data?categoryIds=${categoryIds.join(',')}&code=${code}&minute=${minutes}`
			);

			if (!response.ok) {
				throw new Error(`网络错误: ${response.status}`);
			}

			const result = await response.json();

			if (result.code !== "00" || !result.success) {
				throw new Error(`API错误: ${result.message}`);
			}

			return result.data;
		} catch (error) {
			console.error('获取数据失败:', error);
			return null;
		}
	}

	// 刷新数据
	async function reloadData() {
		const content = document.getElementById('content');
		const oldContent = content.innerHTML;

		// 显示加载动画
		content.innerHTML = `
                <div class="loading-container">
                    <div class="loading"></div>
                </div>
            `;

		try {
			const { code } = getUrlParams();
			const data = await fetchData();
			renderData(data, code);
		} catch (error) {
			console.error('刷新数据失败:', error);
			content.innerHTML = oldContent;
			alert('数据加载失败，请重试');
		}
	}

	// 初始化页面
	async function init() {
		// 初始加载数据
		await reloadData();

		// 设置自动刷新
		const refreshInterval = document.getElementById('refreshInterval');
		let refreshTimer;

		function setRefreshTimer() {
			clearInterval(refreshTimer);
			const minutes = parseInt(refreshInterval.value);
			refreshTimer = setInterval(reloadData, minutes * 60000);
		}

		refreshInterval.addEventListener('change', setRefreshTimer);
		document.getElementById('manualRefresh').addEventListener('click', reloadData);

		// 默认1分钟刷新
		setRefreshTimer();
	}

	// 页面加载完成后初始化
	window.addEventListener('load', init);
</script>
</body>
</html>